﻿using System;
using System.Linq;
using System.Threading;

namespace ECommerce.Controls
{
	public partial class ListLanguages : BaseUserControl
	{
		private Service.ILanguageService _LanguageService;
		private int _CurrentLanguageID;

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				if (SiteContext.Current == null)
				{
					return;
				}
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			BindLanguages();
		}

		protected void RepeaterLanguages_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e)
		{
			if (e.CommandName == "Select")
			{
				if (e.CommandArgument != null)
				{
					_CurrentLanguageID = Convert.ToInt32(e.CommandArgument);

					LocalizationManager.ChangeCurrentCulture(_CurrentLanguageID);
				}
			}
		}

		protected void RepeaterLanguages_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
		{
			if (e.Item.DataItem != null)
			{
				var LinkButtonLangChg = e.Item.FindControl("LinkButtonLangChg") as System.Web.UI.WebControls.LinkButton;

				if (_CurrentLanguageID > 0)
				{
					LinkButtonLangChg.Enabled = !LinkButtonLangChg.CommandArgument.Equals(_CurrentLanguageID.ToString());
				}
				else
				{
					var context = SiteContext.Current;
					if (context != null)
					{
						var lang = context.WorkingLanguage;

						if (lang != null)
						{
							LinkButtonLangChg.Enabled = !LinkButtonLangChg.CommandArgument.Equals(lang.LanguageId.ToString());
						}
					}
				}
			}
		}

		private void BindLanguages()
		{
			if (_LanguageService == null)
			{
				_LanguageService = new Service.LanguageService();
			}

			var languages = _LanguageService.GetAllLanguage();

			RepeaterLanguages.DataSource = languages;
			RepeaterLanguages.DataBind();
		}
	}
}